/*
 @name: keywords.js
 @description: 关键词订阅
 @require: vus.js jQuery.js
 @date: 2015/9/6
 @author: Nero(Nero@Nero-zou.com)
 */
/**
 * 关键词订阅
 */
var LoginWXB=window.top.LoginWXB;
var App={
    showLoading: function (target) {
        var oldHtml = target.html();
        target.addClass('js-loading disabled');
        var fa= target.find('i.fa');
        if(fa.length===0){
            try{
                target.prepend('<i class="fa fa-spinner fa-loading"></i> ');
            }catch (e){

            }
        }else{
            fa.attr('class','fa fa-spinner fa-loading');
        }
        return {
            revert: function () {
                target.html(oldHtml);
                target.removeClass('js-loading disabled');
            }
        };
    }
}
Vue.filter('msgType', function (type) {
    var map = {
        "0": "图文",
        "1": "视频"
    }
    return map[type]
});
Vue.filter('msgTime', function (time) {
    var date = new Date(time * 1000);
    var year = date.getFullYear();
    var month = (date.getMonth() + 1) < 10 ? '0' + (date.getMonth() + 1) : (date.getMonth() + 1);
    var day = (date.getDate()) < 10 ? '0' + (date.getDate()) : (date.getDate());
    var hour = (date.getHours()) < 10 ? '0' + (date.getHours()) : (date.getHours());
    var minute = (date.getMinutes()) < 10 ? '0' + (date.getMinutes()) : (date.getMinutes());
    var seconds = (date.getSeconds()) < 10 ? '0' + (date.getSeconds()) : (date.getSeconds());
    var times = year + '-' + month + '-' + day + ' ' + hour + ':' + minute + ':' + seconds;
    return times;
});
var vm = new Vue({
    el: '#keywords',
    data: {
        isInEditKeys:false,//是否正在管理关键词
        keyNum: 0,
        keyId: 0,
        keys: [],
        article: [],
        data:[],
        page:1,
        keySelect:[],
        article_list_no:false,
        pageNum:12,
        n:1,
        nowActiveKey:'',
        sortKey: null
    },
    methods: {
        //获取关键词
        getKeys: function () {
            var _this = this;
            LoginWXB.getKeywordsList().then(function (response) {
                if (!response.data.length) return;
                _this.keys = response.data;
                _this.showArticle(_this.keys[0]);
            }).catch(function (err) {
                toastr.error(err,"加载关键词失败");
            });
        },
        //添加关键词
        addKeys: function () {
            var _this = this;
            var _keyword = $('#keys-name').val().trim();
            var newKey = {
                keyword: _keyword
            };
            var _keys = _this.keys;
            for (var n = 0; n < _keys.length; n++) {
                if (_keyword == _keys[n].keyword) {
                    toastr.error("", "已添加该关键词！");
                    return;
                }
            }
            if (_keyword == '') {
                toastr.error("", "请输入关键词！");
                return;
            } else if (_keyword.length > 7) {
                var confirm = Win.confirm({
                    title: '提示',
                    content: '<div class="warning-box">关键词输入不超过7个字符！</div>'
                });
                return;
            } else if (_keys.length >= 20) {
                var confirm = Win.confirm({
                    title: '提示',
                    content: '<div class="warning-box">关键词输入不能超过20个！</div>'
                });
                return;
            } else {
                var loading = App.showLoading($('.js-add-btn'));
                LoginWXB.keywordsSave(_keyword).then(function (response) {
                    loading.revert();
                    _keys.push(newKey);
                }).catch(function (err) {
                    toastr.error(err, '添加失败');
                });
            }
        },
        //删除关键词
        deleteKeys: function (key, e) {
            e.stopPropagation();
            var id = key.id;
            if(!id){
                toastr.error("","请刷新页面，再删除这个关键词");
                return;
            }
            var _this = this;
            var k = _this.keys;
            var confirm = Win.confirm({
                title: '提示',
                content: '<div class="warning-box">确定删除关键词 “' + key.keyword + '”</div>',
                yesFunc: function () {

                    LoginWXB.keywordsDel(id).then(function (response) {
                        for (var n = 0; n < k.length; n++) {
                            if (id == k[n].id) {
                                k.splice(n, 1);
                            }
                        }
                    }).catch(function (err) {
                        toastr.error(err,"删除失败");
                    });
                }
            });
            return;
        },
        //管理关键词
        manageKeys: function () {
            this.isInEditKeys=!this.isInEditKeys;
            $('.js-keys-ctn li').toggleClass('keys-close');
        },
        showArticle:function(key){
            this.nowActiveKey=key.id;
            this.updateKeys((key.keyword),2)
        },
        //更新文章
        updateKeys: function (q,btn, order) {
            var _this = this;
            _this.data=[];
            _this.n=1;
            _this.keySelect=[];
            if(btn==1){
                var confirm = Win.confirm({
                    title: '更新我订阅的关键词文章',
                    content: '<div class="progress"><div class="progress_ctn move"></div></div>'+
                    '<div class="warning-box">更新文章中</div>'
                });
            }
            var loading = App.showLoading($('.js-update-btn'));
            LoginWXB.getKeywordsArticles(q, order).then(function (response) {
                _this.article = response.data;
                _this.data=_this.article.slice(0,10);
                _this.keySelect.push(q);
                if(_this.article.length>10){
                    _this.article_list_no=true;
                }
                else{
                    _this.article_list_no=false;
                }
                loading.revert();
                if (confirm) {
                    confirm.modal('hide');
                }
            }).catch(function () {
                $('.progress').hide();
                $(".warning-box").html("更新出错，请稍后再试");
                $(".warning-box").css("color","red");
                toastr.error("服务器繁忙","获取文章");
            });
        },
        sortByRead: function(sortKey){
            var self = this;
            this.sortKey = sortKey;
            var key = this.keys.filter(function(item){
                return item.id === self.nowActiveKey;
            })[0];
            this.updateKeys((key.keyword), 2, sortKey);
        },
        goToLink:function(link){
            if(link){
                window.top.openUrlToBrowser(link);
            }
        },
        clickAddMaterial: function (obj, e) {
            //materialSythesizer.add(obj, e.target);
        },
        loadMore:function(){
            var _this=this;
            var article_list=_this.article;
            var n=(_this.n)++;
            var dataRequest=article_list.slice(n*10,(n*10+10));
            _this.data=_this.data.concat(dataRequest);
            if((n*10+10)>=article_list.length){
                _this.article_list_no=false;
            }else{
                _this.article_list_no=true;
            }


        },

        clickAddMaterial: function(obj, e) {
            console.log(obj);
            var offset=$(e.target).offset();
            offset.left=offset.left+190;
            offset.top=offset.top+90;
            window.top.Material.addMaterialToCart(obj.url,offset);
        },
        clickAddMaterialElse:function(obj){
            window.top.Material.addMaterialToElseCart(obj.url);
        },
    }
});
